﻿/****************************************************** 
Writer:Du YanMing
Mail:dym880@163.com
Create Date:2020/7/3 16:36:39 
Functional description： RouterModule
******************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Anno.Const.Attribute;
using Anno.EngineData;

namespace Anno.DynamicApi
{
    using Anno.Rpc;
    using Anno.Rpc.Client;
    using Anno.Rpc.Storage;
    [RoutePrefix("Dynamic/Api")]
    public class DynamicApiModule : BaseModule
    {
        #region GetServices
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "DynamicApi 集合")]
        public ActionResult GetServices()
        {
            List<ServiceInformation> list = new List<ServiceInformation>();
            List<Micro> list2 = (from m in Connector.Micros
                                 where m.Tags.Contains("Anno.DynamicApi")
                                 select m.Mi).ToList<Micro>();
            if (list2 != null && list2.Count > 0)
            {
                using (List<Micro>.Enumerator enumerator = list2.GetEnumerator())
                {
                    while (enumerator.MoveNext())
                    {
                        Micro service = enumerator.Current;
                        if (!list.Any((ServiceInformation it) => it.Host == service.Ip && it.Port == service.Port))
                        {
                            list.Add(new ServiceInformation
                            {
                                Host = service.Ip,
                                Port = service.Port,
                                Timeout = service.Timeout,
                                Weight = service.Weight,
                                Nickname = service.Nickname,
                                Path = service.Path
                            });
                        }
                    }
                }
            }
            return ResultOk(list);
        }
        #endregion

        #region 动态接口管理
        #region 控制器
        /// <summary>
        /// 获取控制器菜单
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "获取第三方地址")]
        public ActionResult GetControllerMenus()
        {
            var css = new List<object>();
            try
            {
                foreach (var cs in ControllerList.ControllerBuilderInfos)
                {
                    if (cs.ControllerName.IsNullOrEmpty_()) continue;

                    var children = new List<object>();
                    foreach (var api in cs.ApiInfoList)
                    {
                        children.Add(new { label = api.Title, dropdownShow = false, Id = api.KeyWord, PId = api.ControllerName, Name = api.ApiName, api.Title, Remark = api.Remark, Level = 1, api.HttpMethod, children = new List<object>() });
                    }

                    css.Add(new { label = cs.Title, dropdownShow = false, Id = cs.ControllerName, cs.Title, PId = "", Name = cs.ControllerName, Remark = cs.Remark, Level = 0, DefaultDBName = cs.DefaultDBName, RoutePrefix = cs.RoutePrefix, children = children });

                }
                return ResultOk(css);
            }
            catch (Exception ex)
            {
                Anno.Log.Log.Error(ex, "GetControllerGroup");
                return ResultError(ex);
            }
        }
        /// <summary>
        /// 获取所有控制器（项目）集合
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "获取所有控制器（项目）集合")]
        public ActionResult GetControllers()
        {
            //var GroupId = this.RequestString("GroupId");
            var ControllerName = this.RequestString("Name");
            var css = new List<object>();
            try
            {
                foreach (var cs in ControllerList.ControllerBuilderInfos)
                {
                    //if (!string.IsNullOrWhiteSpace(GroupId) && !cs.GroupId.Equals(GroupId, StringComparison.OrdinalIgnoreCase))
                    //    continue;
                    if (!string.IsNullOrWhiteSpace(ControllerName) && !cs.ControllerName.Equals(ControllerName, StringComparison.OrdinalIgnoreCase))
                        continue;
                    css.Add(cs.JObject);
                }
                return ResultOk(css);
            }
            catch (Exception ex)
            {
                Anno.Log.Log.Error(ex, "GetControllers");
                return ResultError(ex);
            }
        }
        /// <summary>
        /// 保存控制器（项目）
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "保存控制器（项目）")]
        public ActionResult SaveController()
        {
            try
            {
                var ControllerName = this.RequestString("Name");
                var RoutePrefix = this.RequestString("RoutePrefix", "api/" + ControllerName);// /HCenter;
                var Namespace = this.RequestString("Namespace", "HCenter.DynamicApi").TrimEnd('.');
                var DefaultDBName = this.RequestString("DefaultDBName", "BaseDb");
                var Title = this.RequestString("Title", ControllerName);
                var Remark = this.RequestString("Remark");
                var IsCamelCaseNames = this.RequestString("IsCamelCaseNames", "false").ChangeType<bool>();

                if (string.IsNullOrWhiteSpace(ControllerName))
                    return ResultFaild("保存失败,Name不能为空");

                var cs = ControllerList.ControllerBuilderInfos.Find(f => f.ControllerName.Equals(ControllerName, StringComparison.OrdinalIgnoreCase));
                if (cs != null)
                {
                    cs.RoutePrefix = RoutePrefix;
                    cs.Namespace = Namespace;
                    cs.DefaultDBName = DefaultDBName;
                    cs.Title = Title;
                    cs.Remark = Remark;
                    cs.IsCamelCaseNames = IsCamelCaseNames;
                }
                else
                {
                    cs = new ControllerInfo();
                    cs.ControllerName = ControllerName;
                    cs.RoutePrefix = RoutePrefix;
                    cs.Namespace = Namespace;
                    cs.DefaultDBName = DefaultDBName;
                    cs.Title = Title;
                    cs.Remark = Remark;
                    cs.IsCamelCaseNames = IsCamelCaseNames;

                    ControllerList.ControllerBuilderInfos.Add(cs);
                }

                var xnode = ControllerList.SingleXml.SelectSingleNode(@"configuration/Controller", "Name", ControllerName);
                if (xnode != null && xnode is System.Xml.XmlElement xe)
                {
                    ControllerList.SingleXml.SetAttributes(xe, cs.DicAttrs);
                    ControllerList.SingleXml.SaveXmlDoc();
                }
                else
                {
                    xnode = ControllerList.SingleXml.InsertNode("Controller", true, "configuration", cs.DicAttrs);
                }

                return ResultOk("保存成功");
            }
            catch (Exception ex)
            {
                Anno.Log.Log.Error(ex, "SaveController");
                return ResultError(ex);
            }
        }
        /// <summary>
        /// 删除控制器（项目）
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "删除控制器（项目）")]
        public ActionResult DelController()
        {
            try
            {
                var ControllerName = this.RequestString("Name");
                if (!string.IsNullOrWhiteSpace(ControllerName))
                {
                    var cs = ControllerList.ControllerBuilderInfos.Find(f => f.ControllerName.Equals(ControllerName, StringComparison.OrdinalIgnoreCase));
                    if (cs != null && cs.ApiInfoList?.Count > 0)
                    {
                        return ResultFaild($"删除失败,【{ControllerName}】中接口集合不为空，不能删除");
                    }

                    var xnode = ControllerList.SingleXml.SelectSingleNode(@"configuration/Controller", "Name", ControllerName);
                    if (xnode != null && xnode is System.Xml.XmlElement xe)
                    {
                        if (ControllerList.SingleXml.DeleteXmlNodeByXPath(@"configuration/Controller", "Name", ControllerName))
                        {
                            ControllerList.ControllerBuilderInfos.Remove(cs);
                            return ResultOk("删除成功");
                        }
                        else
                        {
                            return ResultFaild($"删除【{ControllerName}】失败");
                        }
                    }
                    return ResultFaild($"删除失败,【{ControllerName}】不存在");
                }
                return ResultFaild("删除失败,Name不能为空");
            }
            catch (Exception ex)
            {
                Anno.Log.Log.Error(ex, "DelController");
                return ResultError(ex);
            }
        }
        #endregion
        #region 接口
        /// <summary>
        /// 获取接口集合
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "获取接口集合")]
        public ActionResult GetApiInfo()
        {
            var css = new List<object>();
            try
            {
                int page = this.RequestInt32("page") ?? 1;
                int pagesize = this.RequestInt32("pagesize") ?? 20;
                var controllerName = this.RequestString("ControllerName");
                var KeyWord = this.RequestString("KeyWord");
                long totalNumber = 0;
                //-------------------------------------------------------------------------------------------------
                if (!string.IsNullOrWhiteSpace(KeyWord))//获取单个接口信息
                {
                    if (ControllerList.DicApiInfo.TryGetValue(KeyWord, out var api) && api != null)
                    {
                        css.Add(api.JObject);
                        totalNumber = 1;
                    }
                    else
                    {
                        return ResultFaild($"未找到KeyWord为【{KeyWord}】相关信息");
                    }
                }
                else
                {
                    //-------------------------------------------------------------------------------------------------
                    int currIdx = (page > 1 ? (page - 1) * pagesize : 0);
                    if (string.IsNullOrWhiteSpace(controllerName))//获取指定控制器接口信息
                    {
                        var list = ControllerList.DicApiInfo.Values.ToList<ApiInfo>();
                        totalNumber = list.Count;
                        for (int i = 0; i < pagesize && i < list.Count - currIdx; i++)
                        {
                            var api = list[currIdx + i];
                            css.Add(api.JObject);
                        }
                    }
                    else
                    {
                        var cs = ControllerList.ControllerBuilderInfos.Find(f => f.ControllerName.Equals(controllerName, StringComparison.OrdinalIgnoreCase));
                        if (cs != null)
                        {
                            totalNumber = cs.ApiInfoList.Count;
                            for (int i = 0; i < pagesize && i < cs.ApiInfoList.Count - currIdx; i++)
                            {
                                var api = cs.ApiInfoList[currIdx + i];
                                css.Add(api.JObject);
                            }
                        }
                        else
                        {
                            return ResultFaild($"未找到【{controllerName}】相关信息");
                        }
                    }
                }
                var output = new Dictionary<string, object> { { "Total", totalNumber }, { "Rows", css }, { "PageSize", pagesize }, { "PageIndex", page } };
                return ResultOk(output);
            }
            catch (Exception ex)
            {
                Anno.Log.Log.Error(ex, "GetApiInfo");
                return ResultError(ex);
            }
        }
        /// <summary>
        /// 删除接口
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "删除接口")]
        public ActionResult DelApiInfo()
        {
            try
            {
                var ControllerName = this.RequestString("ControllerName");
                if (string.IsNullOrWhiteSpace(ControllerName))
                    return ResultFaild("保存失败,ControllerName不能为空");

                var ApiName = this.RequestString("ApiName");
                if (string.IsNullOrWhiteSpace(ApiName))
                    return ResultFaild("保存失败,ApiName不能为空");

                var cs = ControllerList.ControllerBuilderInfos.Find(f => f.ControllerName.Equals(ControllerName, StringComparison.OrdinalIgnoreCase));
                if (cs == null || cs.ApiInfoList?.Count == 0)
                {
                    return ResultFaild($"删除失败,【{ControllerName}】中接口集合为空");
                }

                var xnode = ControllerList.SingleXml.SelectSingleNode($@"configuration/Controller{ControllerList.SingleXml.TranslateStr("Name", ControllerName)}/Api", "Name", ApiName);
                if (xnode != null && xnode is System.Xml.XmlElement xe)
                {
                    if (ControllerList.SingleXml.DeleteXmlNodeByXPath($@"configuration/Controller{ControllerList.SingleXml.TranslateStr("Name", ControllerName)}/Api", "Name", ApiName))
                    {
                        var api = cs.ApiInfoList.Find(r => r.ApiName.Equals(ApiName, StringComparison.OrdinalIgnoreCase));
                        if (api != null)
                        {
                            cs.ApiInfoList.Remove(api);
                            ControllerList.DicApiInfo.TryRemove(api.KeyWord, out api);
                        }
                        return ResultOk("删除成功");
                    }
                    else
                    {
                        return ResultFaild($"删除【{ControllerName}/{ApiName}】失败");
                    }
                }
                return ResultFaild($"删除失败,【{ControllerName}/{ApiName}】不存在");

            }
            catch (Exception ex)
            {
                Anno.Log.Log.Error(ex, "DelApiInfo");
                return ResultError(ex);
            }
        }
        /// <summary>
        /// 保存接口
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "保存接口")]
        public ActionResult SaveApiInfo()
        {
            try
            {
                //var inputData = reg.InputData();
                var ControllerName = this.RequestString("ControllerName");
                var RoutePrefix = this.RequestString("RoutePrefix", "api/" + ControllerName);// /HCenter;
                var Namespace = this.RequestString("Namespace", "HCenter.DynamicApi").TrimEnd('.');

                var ApiName = this.RequestString("Name");
                var HttpMethod = this.RequestString("HttpMethod", "POST").Trim().ToUpper();
                var Route = this.RequestString("Route", ApiName);
                var MultiExecutor = this.RequestString("MultiExecutor", "false").ChangeType<bool>();
                var Title = this.RequestString("Title", ControllerName);
                var Remark = this.RequestString("Remark");
                var Stat = this.RequestString("Stat", "1").ChangeType<int>();
                var IsCamelCaseNames = this.RequestString("IsCamelCaseNames", "false").ChangeType<bool>();

                if (string.IsNullOrWhiteSpace(ControllerName))
                    return ResultFaild("保存失败,ControllerName不能为空");
                if (string.IsNullOrWhiteSpace(ApiName))
                    return ResultFaild("保存失败,Name不能为空");

                var cs = ControllerList.ControllerBuilderInfos.Find(f => f.ControllerName.Equals(ControllerName, StringComparison.OrdinalIgnoreCase));
                if (cs == null)
                {
                    return ResultFaild($"保存失败,【{ControllerName}】不存在");
                }

                var ExecutorList = this.Request<Newtonsoft.Json.Linq.JArray>("ExecutorList");
                if (ExecutorList == null || ExecutorList.Count == 0)
                    return ResultFaild("保存失败,ExecutorList不能为空");
                //--------------------------------------------------------------------------------------------------------
                //RoutePrefix = PathUtil.GetBaseRoute(RoutePrefix, ControllerName);
                var apii = new ApiInfo(Namespace, ControllerName)
                {
                    ApiName = ApiName,
                    HttpMethod = HttpMethod,
                    Route = Route,
                    MultiExecutor = MultiExecutor,
                    Title = Title,
                    Remark = Remark,
                    Stat = Stat,
                    IsCamelCaseNames = IsCamelCaseNames,
                    BaseRoute = RoutePrefix,
                };
                apii.InitExecutorList(ExecutorList, cs);

                #region save Api
                var xnode = ControllerList.SingleXml.SelectSingleNode($@"configuration/Controller{ControllerList.SingleXml.TranslateStr("Name", ControllerName)}/Api", "Name", ApiName);
                if (xnode != null && xnode is System.Xml.XmlElement xe)//修改Api
                {
                    xnode.RemoveAll();
                    ControllerList.SingleXml.SetAttributes(xe, apii.DicAttrs);
                    cs.ApiInfoList.RemoveAll(f => f.KeyWord.Equals(apii.KeyWord, StringComparison.OrdinalIgnoreCase));
                }
                else//新增Api
                {
                    var cnode = ControllerList.SingleXml.SelectSingleNode(@"configuration/Controller", "Name", ControllerName);
                    #region Controller
                    if (cnode == null)
                    {
                        cs.ControllerName = ControllerName;
                        cs.RoutePrefix = RoutePrefix;
                        cs.Namespace = Namespace;
                        cs.Title = Title;
                        cs.Remark = Remark;
                        cs.IsCamelCaseNames = IsCamelCaseNames;
                        cnode = ControllerList.SingleXml.InsertNode("Controller", true, "configuration", cs.DicAttrs, null, false);
                    }
                    #endregion

                    xnode = ControllerList.SingleXml.InsertNode("Api", true, cnode, apii.DicAttrs, null, false);
                }
                #region saveExecutor
                var executorsNode = ControllerList.SingleXml.InsertNode("Executors", false, xnode, null, null, false);

                Action<System.Xml.XmlNode, BaseExecutor> saveExecutors = null;
                Action<System.Xml.XmlNode, ApiFieldInfo, string> saveInputs = null;
                saveInputs = (pNode, input, nodeName) =>
                {
                    //Input
                    var snode = ControllerList.SingleXml.InsertNode(nodeName, true, pNode, input.DicAttrs, null, false);
                    //Inputs
                    if (input.HasSub)
                    {
                        //SubFieldInfoList
                        input.SubFieldInfoList.ForEach(sinput =>
                        {
                            saveInputs(snode, sinput, "FieldInfo");
                        });
                    }
                };
                saveExecutors = (pNode, exc) =>
                {
                    //Executor
                    var snode = ControllerList.SingleXml.InsertNode("Executor", true, pNode, exc.DicAttrs, null, false);

                    //Inputs
                    if (exc.HasInput)
                    {
                        var inputsnode = ControllerList.SingleXml.InsertNode("Inputs", false, snode, null, null, false);
                        exc.ApiInputInfoList.ForEach(input =>
                        {
                            saveInputs(inputsnode, input, "Input");
                        });
                    }

                    if (exc.ExecType == ExecutorType.SqlTpl && exc is SqlTplExecutor tplExecutor)
                    {
                        //Outputs
                        #region Outputs
                        if (tplExecutor?.OutputList?.Count > 0)
                        {
                            var outputsnode = ControllerList.SingleXml.InsertNode("Outputs", false, snode, null, null, false);
                            tplExecutor.OutputList.ForEach(output =>
                            { //Output
                                var soutputsnode = ControllerList.SingleXml.InsertNode("Output", true, outputsnode, output.DicAttrs, null, false);
                                if (output.HasOutput)
                                {
                                    output.ApiInputInfoList.ForEach(outsput =>
                                    { //Output
                                        saveInputs(soutputsnode, outsput, "FieldInfo");
                                    });
                                }
                            });
                        }
                        #endregion
                    }

                    //Conditions
                    if (exc.Conditions?.Count > 0)
                    {
                        var conditionsnode = ControllerList.SingleXml.InsertNode("Conditions", true, snode, exc.Conditions.DicAttrs, null, false);
                        exc.Conditions.ForEach(condition =>
                        {
                            var conditionnode = ControllerList.SingleXml.InsertNode("Condition", true, conditionsnode, condition.DicAttrs, null, false);
                        });
                    }

                    //NextExecutors
                    exc.NextExecutors?.ForEach(excs =>
                    {
                        saveExecutors(snode, excs);
                    });
                };

                apii.ExecutorList.ForEach(exc =>
                {
                    saveExecutors(executorsNode, exc);
                });
                #endregion

                #endregion

                ControllerList.SingleXml.SaveXmlDoc();
                ControllerList.DicApiInfo[apii.KeyWord] = apii;
                cs.ApiInfoList.Add(apii);

                return ResultOk("保存成功|" + apii.KeyWord);
            }
            catch (Exception ex)
            {
                Anno.Log.Log.Error(ex, "SaveApiInfo");
                return ResultError(ex);
            }
        }
        #endregion
        #endregion

        #region 第三方地址
        /// <summary>
        /// 获取第三方地址
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "获取第三方地址")]
        public ActionResult GetUriInfo()
        {
            var css = new List<object>();
            try
            {
                var Name = this.RequestString("Name");

                foreach (var cs in ControllerList.DicBaseUri)
                {
                    if (!string.IsNullOrWhiteSpace(Name) && !cs.Key.ToLower().Contains(Name.ToLower()))
                        continue;
                    if (cs.Value.IsNotNullOrEmpty_())
                        css.Add(cs.Value.JObject);
                }
                return ResultOk(css);
            }
            catch (Exception ex)
            {
                Anno.Log.Log.Error(ex, "GetUriInfo");
                return ResultError(ex);
            }
        }
        /// <summary>
        /// 保存第三方地址
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "保存第三方地址")]
        public ActionResult SaveUriInfo()
        {
            try
            {
                var Name = this.RequestString("Name");
                var BaseUri = this.RequestString("BaseUri");
                var Remark = this.RequestString("Remark");

                if (string.IsNullOrWhiteSpace(Name))
                    return ResultFaild("保存失败,Name不能为空");
                if (string.IsNullOrWhiteSpace(BaseUri))
                    return ResultFaild("保存失败,BaseUri不能为空");

                if (!string.IsNullOrWhiteSpace(BaseUri))
                {
                    if (ControllerList.DicBaseUri.TryGetValue(Name, out var remoteUri))
                    {
                        remoteUri.BaseUri = BaseUri;
                        remoteUri.Remark = Remark;

                        var xnode = ControllerList.SingleXml.SelectSingleNode(@"configuration/RemoteUris/RemoteUri", "Name", Name);
                        if (xnode != null && xnode is System.Xml.XmlElement xe)
                        {
                            ControllerList.SingleXml.SetAttributes(xe, remoteUri.DicAttrs);
                            ControllerList.SingleXml.SaveXmlDoc();
                        }
                        else { ControllerList.SingleXml.InsertNode("RemoteUri", true, "configuration/RemoteUris", remoteUri.DicAttrs); }
                    }
                    else
                    {
                        remoteUri = new RemoteUriInfo() { Name = Name, BaseUri = BaseUri, Remark = Remark };
                        ControllerList.DicBaseUri[Name] = remoteUri;
                        ControllerList.SingleXml.InsertNode("RemoteUri", true, "configuration/RemoteUris", remoteUri.DicAttrs);
                    }

                    return ResultOk("保存成功");
                }
                return ResultFaild("保存失败,【BaseUri】不能为空");
            }
            catch (Exception ex)
            {
                Anno.Log.Log.Error(ex, "SaveUriInfo");
                return ResultError(ex);
            }
        }
        /// <summary>
        /// 删除第三方地址
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "删除第三方地址")]
        public ActionResult DelUriInfo()
        {
            try
            {
                var Name = this.RequestString("Name");
                if (!string.IsNullOrWhiteSpace(Name))
                {
                    var xnode = ControllerList.SingleXml.SelectSingleNode(@"configuration/RemoteUris/RemoteUri", "Name", Name);
                    if (xnode != null && xnode is System.Xml.XmlElement xe)
                    {
                        if (ControllerList.SingleXml.DeleteXmlNodeByXPath(@"configuration/RemoteUris/RemoteUri", "Name", Name))
                        {
                            ControllerList.DicBaseUri.TryRemove(Name, out var uriInfo);
                            return ResultOk("删除成功");
                        }
                        else
                        {
                            return ResultFaild($"删除【{Name}】失败");
                        }
                    }
                    return ResultFaild($"删除失败,【{Name}】不存在");
                }
                return ResultFaild("删除失败,Name不能为空");
            }
            catch (Exception ex)
            {
                Anno.Log.Log.Error(ex, "DelUriInfo");
                return ResultError(ex);
            }
        }
        #endregion

        #region 数据库连接配置
        /// <summary>
        /// 获取数据库连接配置
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "获取数据库连接配置")]
        public ActionResult GetConnectionStrings()
        {
            var css = new List<dynamic>();
            try
            {
                var Name = this.RequestString("Name");
                if (string.IsNullOrWhiteSpace(Name) || Repository.SqlSugarSetup.ConnectionStringsConfig.DefaultDbNumber.ToLower().Equals(Name.ToLower()))
                { css.Add(new { Name = Repository.SqlSugarSetup.ConnectionStringsConfig.DefaultDbNumber, ConnectionString = Repository.SqlSugarSetup.ConnectionStringsConfig.DefaultDbString, ProviderName = Repository.SqlSugarSetup.ConnectionStringsConfig.DefaultDbType, IsDefault = true }); }
                foreach (var cs in Anno.Repository.SqlSugarSetup.ConnectConfigList)
                {
                    if (!string.IsNullOrWhiteSpace(Name) && !cs.ConfigId.ToLower().Equals(Name.ToLower()))
                        continue;
                    if (css.Any(a => a.Name == cs.ConfigId))
                    {
                        continue;
                    }
                    css.Add(new { Name = cs.ConfigId.ToString(), cs.ConnectionString, ProviderName = cs.DbType.ToString(), IsDefault = false });
                }
                return ResultOk(css);
            }
            catch (Exception ex)
            {
                Anno.Log.Log.Error(ex, "GetConnectionStrings");
                return ResultError(ex);
            }
        }
        /// <summary>
        /// 保存数据库连接配置
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "保存数据库连接配置")]
        public ActionResult SaveConnectionString()
        {
            try
            {
                var Name = this.RequestString("Name");
                var ConnectionString = this.RequestString("ConnectionString");
                var ProviderName = this.RequestString("ProviderName");
                if (string.IsNullOrWhiteSpace(Name))
                    return ResultFaild("保存失败,Name不能为空");
                if (!string.IsNullOrWhiteSpace(ConnectionString) && !string.IsNullOrWhiteSpace(ProviderName))
                {
                    #region ConnectConfigList
                    var connection = Anno.Repository.SqlSugarSetup.ConnectConfigList.Find(f => Name.Equals(f.ConfigId, StringComparison.OrdinalIgnoreCase));
                    if (connection != null)
                    {
                        connection.ConnectionString = ConnectionString;
                        connection.DbType = ProviderName.ToEnum_<SqlSugar.DbType>();
                    }
                    else
                    {
                        Anno.Repository.SqlSugarSetup.ConnectConfigList.Add(new SqlSugar.ConnectionConfig
                        {
                            ConnectionString = ConnectionString,
                            DbType = ProviderName.ToEnum_<SqlSugar.DbType>(),
                            IsAutoCloseConnection = true,
                            ConfigId = Name,
                            InitKeyType = SqlSugar.InitKeyType.Attribute,
                            MoreSettings = new SqlSugar.ConnMoreSettings()
                            {
                                IsAutoRemoveDataCache = true//自动清理缓存
                            }
                        });
                    }
                    #endregion
                    #region ConnectionStringsConfig
                    if (Repository.SqlSugarSetup.ConnectionStringsConfig.DefaultDbNumber.Equals(Name, StringComparison.OrdinalIgnoreCase))
                    {
                        Repository.SqlSugarSetup.ConnectionStringsConfig.DefaultDbString = ConnectionString;
                        Repository.SqlSugarSetup.ConnectionStringsConfig.DefaultDbType = ProviderName;
                    }
                    else
                    {
                        var connectionc = Repository.SqlSugarSetup.ConnectionStringsConfig.DbConfigs.Find(f => Name.Equals(f.DbNumber, StringComparison.OrdinalIgnoreCase));
                        if (connectionc != null)
                        {
                            connectionc.DbString = ConnectionString;
                            connectionc.DbType = ProviderName;
                        }
                        else
                        {
                            Repository.SqlSugarSetup.ConnectionStringsConfig.DbConfigs.Add(new Repository.DbConfig
                            {
                                DbString = ConnectionString,
                                DbType = ProviderName,
                                DbNumber = Name,
                            });
                        }
                    }
                    Repository.SqlSugarSetup.ConnectionStringsConfig.Save();
                    #endregion

                    return ResultOk("保存成功");
                }
                return ResultFaild("保存失败,【ConnectionString,ProviderName】不能为空");
            }
            catch (Exception ex)
            {
                Anno.Log.Log.Error(ex, "SaveConnectionString");
                return ResultError(ex);
            }
        }
        /// <summary>
        /// 删除数据库连接配置
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "删除数据库连接配置")]
        public ActionResult DelConnectionString()
        {
            try
            {
                var Name = this.RequestString("Name");
                if (!string.IsNullOrWhiteSpace(Name))
                {
                    if (Repository.SqlSugarSetup.ConnectionStringsConfig.DefaultDbNumber.Equals(Name, StringComparison.OrdinalIgnoreCase))
                    {
                        return ResultFaild($"删除失败,【{Name}】默认连接地址不能删除");
                    }
                    var connection = Anno.Repository.SqlSugarSetup.ConnectConfigList.Find(f => Name.Equals(f.ConfigId, StringComparison.OrdinalIgnoreCase));
                    if (connection != null)
                    {
                        Anno.Repository.SqlSugarSetup.ConnectConfigList.Remove(connection);

                        var connectionc = Repository.SqlSugarSetup.ConnectionStringsConfig.DbConfigs.Find(f => Name.Equals(f.DbNumber, StringComparison.OrdinalIgnoreCase));
                        if (connectionc != null)
                        {
                            Repository.SqlSugarSetup.ConnectionStringsConfig.DbConfigs.Remove(connectionc);
                            Repository.SqlSugarSetup.ConnectionStringsConfig.Save();
                        }
                        return ResultOk("删除成功");
                    }
                    return ResultFaild($"删除失败,【{Name}】不存在");
                }
                return ResultFaild("删除失败,Name不能为空");
            }
            catch (Exception ex)
            {
                Anno.Log.Log.Error(ex, "DelConnectionString");
                return ResultError(ex);
            }
        }
        #endregion

        #region 环境地址
        /// <summary>
        /// 获取环境地址
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "获取数据库连接配置")]
        public ActionResult GetSetingUriInfo()
        {
            var css = new List<object>();
            try
            {
                var Name = RequestString("Name");

                foreach (var cs in ControllerList.DicSetingUri)
                {
                    if (!string.IsNullOrWhiteSpace(Name) && !cs.Key.ToLower().Contains(Name.ToLower()))
                        continue;
                    if (cs.Value.IsNotNullOrEmpty_())
                        css.Add(cs.Value.JObject);
                }
                return ResultOk(css);
            }
            catch (Exception ex)
            {
                Anno.Log.Log.Error(ex, "GetSetingUriInfo");
                return ResultError(ex);
            }
        }
        /// <summary>
        /// 保存环境地址
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "获取数据库连接配置")]
        public ActionResult SaveSetingUriInfo()
        {
            try
            {
                var Name = RequestString("Name");
                var BaseUri = RequestString("BaseUri");
                var Remark = RequestString("Remark");

                if (string.IsNullOrWhiteSpace(Name))
                    return ResultFaild("保存失败,Name不能为空");
                if (string.IsNullOrWhiteSpace(BaseUri))
                    return ResultFaild("保存失败,BaseUri不能为空");

                if (!string.IsNullOrWhiteSpace(BaseUri))
                {
                    if (ControllerList.DicSetingUri.TryGetValue(Name, out var remoteUri))
                    {
                        remoteUri.BaseUri = BaseUri;
                        remoteUri.Remark = Remark;

                        var xnode = ControllerList.SingleXml.SelectSingleNode(@"configuration/SettingUris/RemoteUri", "Name", Name);
                        if (xnode != null && xnode is System.Xml.XmlElement xe)
                        {
                            ControllerList.SingleXml.SetAttributes(xe, remoteUri.DicAttrs);
                            ControllerList.SingleXml.SaveXmlDoc();
                        }
                        else { ControllerList.SingleXml.InsertNode("RemoteUri", true, "configuration/SettingUris", remoteUri.DicAttrs); }
                    }
                    else
                    {
                        remoteUri = new RemoteUriInfo() { Name = Name, BaseUri = BaseUri, Remark = Remark };
                        ControllerList.DicSetingUri[Name] = remoteUri;
                        ControllerList.SingleXml.InsertNode("RemoteUri", true, "configuration/SettingUris", remoteUri.DicAttrs);
                    }

                    return ResultOk("保存成功");
                }
                return ResultFaild("保存失败,【BaseUri】不能为空");
            }
            catch (Exception ex)
            {
                Anno.Log.Log.Error(ex, "SaveSetingUriInfo");
                return ResultError(ex);
            }
        }
        /// <summary>
        /// 删除环境地址
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "获取数据库连接配置")]
        public ActionResult DelSetingUriInfo()
        {
            try
            {
                var Name = RequestString("Name");
                if (!string.IsNullOrWhiteSpace(Name))
                {
                    var xnode = ControllerList.SingleXml.SelectSingleNode(@"configuration/SettingUris/RemoteUri", "Name", Name);
                    if (xnode != null && xnode is System.Xml.XmlElement xe)
                    {
                        if (ControllerList.SingleXml.DeleteXmlNodeByXPath(@"configuration/SettingUris/RemoteUri", "Name", Name))
                        {
                            ControllerList.DicSetingUri.TryRemove(Name, out var uriInfo);
                            return ResultOk("删除成功");
                        }
                        else
                        {
                            return ResultFaild($"删除【{Name}】失败");
                        }
                    }
                    return ResultFaild($"删除失败,【{Name}】不存在");
                }
                return ResultFaild("删除失败,Name不能为空");
            }
            catch (Exception ex)
            {
                Anno.Log.Log.Error(ex, "DelSetingUriInfo");
                return ResultError(ex);
            }
        }
        #endregion

        #region GetSwageeInfo/HttpRequest
        /// <summary>
        /// 获取接口信息
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "获取接口信息")]
        public ActionResult GetSwageeInfo()
        {
            var api = RequestString("api");
            var url = RequestString("url");
            var dic = new Dictionary<string, object>();
            Action<Dictionary<string, object>, ApiFieldInfo> getInputs = null;
            getInputs = (dics, input) =>
            {
                //Inputs
                if (input.HasSub)
                {
                    var dicsub = new Dictionary<string, object>();
                    //SubFieldInfoList
                    input.SubFieldInfoList.ForEach(sinput =>
                    {
                        getInputs(dicsub, sinput);
                    });
                    dics[input.Name] = dicsub;
                }
                else//Input
                {
                    dics[input.Name] = input.TypeName;
                }
            };
            //var routInfo = ControllerList.DicApiInfo[api];
            if (ControllerList.DicApiInfo.TryGetValue(api, out var routInfo))
            {
                if (routInfo != null && routInfo.ExecutorList?.Count > 0 && routInfo.ExecutorList[0].ApiInputInfoList?.Count > 0)
                {
                    var dics = new Dictionary<string, object>();
                    foreach (var input in routInfo.ExecutorList[0].ApiInputInfoList)
                    {
                        getInputs(dics, input);
                    }
                    dic.Add(routInfo.HttpMethod.ToUpper() == "POST" ? "Properties" : "Parameters", dics);
                }
                return ResultOk(dic);
            }
            return ResultFaild(api+"不存在");
        }
        /// <summary>
        /// 调用远程接口
        /// </summary>
        /// <returns></returns>
        [AnnoInfo(Desc = "调用远程接口")]
        public ActionResult HttpRequest()
        {
            try
            {
                var HttpMethod = RequestString("HttpMethod");
                var Headers = RequestString("Headers");
                var data = RequestString("data");
                var url = RequestString("url");
                string redata = string.Empty;
                List<dynamic> dynamicsHead = JsonHelper.DeserializeObjectByJson<List<dynamic>>(Headers);
                Dictionary<string, string> headers = new Dictionary<string, string>();
                for (int i = 0; dynamicsHead!=null && i < dynamicsHead.Count; i++)
                {
                    headers.Add((dynamicsHead[i].Name.Value as string).NullToStr(), (dynamicsHead[i].value.Value as string).NullToStr());
                }
                Dictionary<string, string> urlparameters = new Dictionary<string, string>();
                if (HttpMethod == "GET")
                {
                    List<dynamic> dynamicsData = JsonHelper.DeserializeObjectByJson<List<dynamic>>(data);
                    string Getdata = string.Empty;
                    for (int i = 0; dynamicsData != null && i < dynamicsData.Count; i++)
                    {
                        urlparameters.Add((dynamicsData[i].name.Value as string).NullToStr(), (dynamicsData[i].value.Value as string).NullToStr());
                    }
                }
                var response = HttpHelper.Instance.RequestAsync(HttpMethod, url, data, headers, urlparameters).Result;
                response.EnsureSuccessStatusCode();
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var retstr = response.Content.ReadAsStringAsync().Result;
                    var jsret = retstr.JsonToObject<object>();

                    return ResultOk(jsret);
                }
                return ResultFaild(response.StatusCode.ToString());
            }
            catch (Exception ex)
            {
                Anno.Log.Log.Error(ex, "HttpRequest");
                return ResultError(ex);
            }
        }
        #endregion
    }
}
